import React, {useContext, useEffect, useState} from "react";
import PostItem from "../components/PostItem";
import Spinner from '../components/Spinner';
import {useNavigate, useParams} from "react-router-dom";
import axios from "axios";
import {Button, Card, NavBar, Toast, Dialog, Tag, Space, Empty, AutoCenter, ErrorBlock,} from "antd-mobile";
import {UserContext} from "../context/userContext";

const AdminPosts = () => {
  const [posts, setPosts] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const {id} = useParams();
  const colors = {'applied':'rgba(80, 62, 157, 1)', 'approved':'rgba(251, 110, 58, 1)', 'failed':'rgba(255, 0, 0, 1)', 'closed':'rgba(255, 0, 0, 1)'};
  const status = {'applied':'待审核', 'approved':'已通过', 'failed':'未通过', 'closed':'已关闭'};
  const navigate = useNavigate();
  const { currentUser } = useContext(UserContext);
  const token = currentUser?.token;

  useEffect(() => {
        if (!token) {
            navigate('/login');
        }
  }, [token, navigate]);
  const back = () =>{
      navigate(-1);
  }
  const closePost = async (id) => {
      setIsLoading(true)
      try {
          const response = await axios.post(`${process.env.REACT_APP_BASE_URL}/posts/close/${id}`)
          console.log(response?.status)
      } catch (err) {
          console.log(err);
      }

      setIsLoading(false)
  };
    const agreePost = async (id) => {
        setIsLoading(true)
        try {
            const response = await axios.post(`${process.env.REACT_APP_BASE_URL}/posts/agree/${id}`)
            console.log(response?.status)
        } catch (err) {
            console.log(err);
        }

        setIsLoading(false)
    };

    const rejectPost = async (id) => {
        setIsLoading(true)
        try {
            const response = await axios.post(`${process.env.REACT_APP_BASE_URL}/posts/reject/${id}`)
            console.log(response?.status)
        } catch (err) {
            console.log(err);
        }

        setIsLoading(false)
    }



  useEffect(() => {

      const fetchPosts = async () => {
          setIsLoading(true)
          if (!currentUser?.id) return;
          try {
              const response = await axios.get(
                  `${process.env.REACT_APP_BASE_URL}/posts/admin/${currentUser.id}`,
                  { withCredentials: true, headers: { Authorization: `Bearer ${token}` } }
              );
              setPosts(response?.data)
          } catch (err) {
              console.log(err);
          }

          setIsLoading(false)
      }

      fetchPosts();
  }, [id])

  if (isLoading) {
      <Spinner />
  }

  return (
      <section className='posts'>
          <NavBar style={{'background-color': 'rgba(80, 62, 157, 1)', 'color': 'white'}} onBack={back}>待审核的项目</NavBar>

          {posts.length > 0 ? <div className='container posts__container'>
              {posts.map(({ _id: id, wages, views, title, status:apply, description, avatar, creator, createdAt }) =>
                  <Card>
                      <Tag style={{'float':'right'}} color={colors[apply]}>{status[apply]}</Tag>
                  <PostItem key={id}
                      postID={id}
                            wages={wages}
                            views={views}
                      title={title}
                      description={description}
                      authorID={creator}
                      createdAt={createdAt}
                      avatar={avatar}
                  />
                      {apply==='applied'&& <div className='footer' onClick={e => e.stopPropagation()}>
                          <Space style={{ '--gap': '29px' }}><Button
                              color='warning'
                              size={"small"}
                              onClick={() => {
                                  Dialog.confirm({
                                      title:'提示',
                                      content: '您确定审批通过该项目吗？',
                                      onConfirm: async () => {
                                          await  agreePost(id);
                                          Toast.show({
                                              icon: 'success',
                                              content: '审批通过',
                                              position: 'bottom',
                                          })
                                      },
                                  })
                              }}
                          >审批通过</Button>
                          <Button
                              color='danger'
                              size={"small"}
                              onClick={() => {
                                  Dialog.confirm({
                                      title:'提示',
                                      content: '您确定审批拒绝该项目吗？',
                                      onConfirm: async () => {
                                          await rejectPost(id);
                                          Toast.show({
                                              icon: 'success',
                                              content: '审批拒绝',
                                              position: 'bottom',
                                          })
                                      },
                                  })
                              }}
                          >审批拒绝</Button></Space>
                      </div>}
                  </Card>  )}
          </div> : <AutoCenter>
              <ErrorBlock image='https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg'
                          style={{'--image-height': '150px'}}
                          title="暂无数据"
                          description=""
                          status='empty' /></AutoCenter>}
      </section>
  )
}

export default AdminPosts
